package designPattern.singleton单例模式.demo5;

public class SingletonDemo05 {

    public static void main(String[] args) {
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
    }
}

// 懒汉式-静态方法-双重检查: 推荐使用
// synchronized 带来新的性能问题: 如果 getInstance 被调用频率过高, 方法级别的同步锁严重影响性能
class Singleton {

    private static volatile Singleton instance;

    private Singleton() {}

    // 调用方法时才创建实例
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

